//
//  SEGDigitalCommunity2TenantViewModel.m
//  SEGViewModel
//
//  Created by 山刘 on 2020/6/24.
//

#import "SEGDigitalCommunity2TenantViewModel.h"

@interface SEGDigitalCommunity2TenantViewModel()
@property (nonatomic, strong, readwrite) RACCommand *requestCommand;
@property (strong, nonatomic, readwrite) RACSubject *messageSubject;
@end

@implementation SEGDigitalCommunity2TenantViewModel
#pragma mark - Init
-(instancetype)init{
    if (self = [super init]) {
        [self racInit];
    }
    return self;
}

- (void)racInit {
    
    @weakify(self);
    
    // 提交人工认证
    _requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            @strongify(self);
            
            self.name = [self.name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            
            NSString *code = @"";
            for (SEGGetdictlistResultlistModel *object in [SEGGetdictlistManager sharedManager].getDictList.data.resultList) {
                if ([object.name isEqualToString:self.userType]) {
                    code = object.code;
                    break;
                }
            }
            
            // 租户成员要比较开始、结束时间
            if([self chcekUserType:self.userType]){
                if (![self checkDate:self.inTime secondDate:self.outTime]) {
                    [self.messageSubject sendNext:@{@"type":@"2",@"value":@"开始时间不得晚于结束时间"}];
                    [subscriber sendCompleted];
                    return nil;
                }
            }else{
                self.inTime = @"";
                self.outTime = @"";
            }
            
            [[SEGSubmitartificialauthManager sharedManager] requestSubmitartificialauthWithHouseid:self.houseId
                                                                                               tel:self.tel
                                                                                              name:self.name
                                                                                          userType:code
                                                                                            inTime:self.inTime
                                                                                           outTime:self.outTime
                                                                                             relId:self.relId
                                                                                          finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                
                if (!isSuccessed) {
                    [self.messageSubject sendNext:@{@"type":@"2",@"value":errorMessage}];
                }else{
                    [subscriber sendNext:nil];
                }
                [subscriber sendCompleted];
            }];
            
            return [RACDisposable disposableWithBlock:^{
            }];
        }];
    }];
    
    // 获取认证类型
    _userTypeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            if (self.userTypeArr.count > 0) {
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                return nil;
            }
            //@strongify(self);
            NSString *type = @"userType";
            [[SEGGetdictlistManager sharedManager] requestGetdictlistWithDicttype:type finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    
                    NSMutableArray *arrM = [NSMutableArray array];
                    for (SEGGetdictlistResultlistModel *object in [SEGGetdictlistManager sharedManager].getDictList.data.resultList) {
                        [arrM addObject:object.name];
                    }
                    self.userTypeArr = [NSArray arrayWithArray:arrM];
                    [subscriber sendNext:nil];
                }else {
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
                [subscriber sendCompleted];
            }];
            return [RACDisposable disposableWithBlock:^{
            }];
        }];
    }];
}

#pragma mark - Publish Methods

/// 判断是否是租户或者租户成员
/// @param type name
-(BOOL)chcekUserType:(NSString*)type{
    for (SEGGetdictlistResultlistModel *object in [SEGGetdictlistManager sharedManager].getDictList.data.resultList) {
        if ([type isEqualToString:object.name]){
            if ([object.value isEqualToString:@"2000"] || [object.value isEqualToString:@"2001"]){
                return YES;
            }
        }
    }
    return NO;
}
/// 检查 确认提交 按钮可点击的状态
-(void)checkSubmitButtonStatus {
    NSArray *signalArr = @[RACObserve(self,houseId),
                           RACObserve(self,tel),
                           RACObserve(self,name),
                           RACObserve(self,userType),
                           RACObserve(self,inTime),
                           RACObserve(self,outTime)];
    RAC(self,submitButtonEnabled) = [RACSignal combineLatest:signalArr reduce:^id (NSString *houseId,
                                                                                   NSString *tel,
                                                                                   NSString *name,
                                                                                   NSString *userType,
                                                                                   NSString *inTime,
                                                                                   NSString *outTime){
        BOOL houseIdStatus = NO;
        if(houseId && houseId.length > 0){
            houseIdStatus = YES;
        }
        BOOL telStatus = NO;
        if (tel && tel.length == 11) {
            telStatus = YES;
        }
        BOOL nameStatus = NO;
        if (name && name.length > 0) {
            nameStatus = YES;
            //判断用户名是否全是空格
            if ([name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length == 0) {
                nameStatus = NO;
            }
        }
        BOOL userTypeStatus = NO;
        BOOL inTimeStatus = NO;
        BOOL outTimeStatus = NO;
        if (userType && userType.length > 0) {
            userTypeStatus = YES;
            if ([self chcekUserType:userType]) { //是租客，需要选择开始、结束时间
                inTimeStatus = (inTime && inTime.length > 0) ? YES : NO;
                outTimeStatus = (outTime && outTime.length > 0) ? YES : NO;
            }else{
             inTimeStatus = YES;
             outTimeStatus = YES;
            }
        }
        
        if(houseIdStatus && telStatus && nameStatus && userTypeStatus && inTimeStatus && outTimeStatus){
            return @(YES);
        }
        return @(NO);
    }];
}

- (NSString *)getUserTypeCode {
    NSString *code = @"";
    for (SEGGetdictlistResultlistModel *object in [SEGGetdictlistManager sharedManager].getDictList.data.resultList) {
        if ([object.name isEqualToString:self.userType]) {
            code = object.code;
            break;
        }
    }
    return code;
}

#pragma mark - Private Methods

/// 时间比较
/// firrstDateString compare secondDateString ->  NSOrderedAscending 降序：firrstDateString时间再secondDateString时间之前。
-(BOOL)checkDate:(NSString*)firrstDateString secondDate:(NSString*)secondDateString{
    NSComparisonResult result = [[self getDate:firrstDateString] compare:[self getDate:secondDateString]];
    if (result == NSOrderedAscending || result == NSOrderedSame) {
        return YES;
    }
    return NO;
}

-(NSDate*)getDate:(NSString*)dateString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    return [dateFormatter dateFromString:dateString];
}

#pragma mark - Getter
-(RACSubject *)messageSubject{
    if (!_messageSubject) {
        _messageSubject = [RACSubject subject];
    }
    return _messageSubject;
}
-(NSArray *)userTypeArr{
    if (!_userTypeArr) {
        _userTypeArr = [NSArray array];
    }
    return _userTypeArr;
}
#pragma mark - Stter
@end
